package com.kxmall.admin.controller.vehicle.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kxmall.common.core.domain.PageQuery;
import com.kxmall.common.core.page.TableDataInfo;
import com.kxmall.common.enums.StorageBusinessStatusType;
import com.kxmall.common.enums.StorageStatusType;
import com.kxmall.common.enums.VehicleStatusType;
import com.kxmall.common.exception.ServiceException;
import com.kxmall.common.utils.BeanCopyUtils;
import com.kxmall.region.domain.KxRegion;
import com.kxmall.region.mapper.KxRegionMapper;
import com.kxmall.storage.domain.KxStorage;
import com.kxmall.storage.domain.vo.KxStorageVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.kxmall.common.utils.redis.RedisUtils;
import com.kxmall.vehicle.domain.KxVehicle;
import com.kxmall.vehicle.domain.bo.KxVehicleBo;
import com.kxmall.vehicle.domain.vo.KxVehicleVo;
import com.kxmall.vehicle.mapper.KxVehicleMapper;
import com.kxmall.admin.controller.vehicle.service.IKxVehicleManageService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 餐车管理Service业务层处理
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class KxVehicleManageServiceImpl implements IKxVehicleManageService {

    private static final String VEHICLE_INFO_PREFIX = "VEHICLE_INFO_";

    @Autowired
    private KxVehicleMapper vehicleMapper;

    @Autowired
    private KxRegionMapper regionMapper;
    /**
     * 查询餐车管理
     */
    @Override
    public KxVehicleVo queryById(Long id) {
        KxVehicleVo kxVehicleVo = new KxVehicleVo();
        KxVehicle kxVehicle = vehicleMapper.selectById(id);
        BeanCopyUtils.copy(kxVehicle, kxVehicleVo);
        if(kxVehicle.getProvince() != null){
            KxRegion kxRegion = regionMapper.selectById(kxVehicle.getProvince());
            kxVehicleVo.setProvinceName(kxRegion.getName());
        }
        if(kxVehicle.getCity() != null){
            KxRegion kxRegion = regionMapper.selectById(kxVehicle.getCity());
            kxVehicleVo.setCityName(kxRegion.getName());
        }
        if(kxVehicle.getCounty() != null){
            KxRegion kxRegion = regionMapper.selectById(kxVehicle.getCounty());
            kxVehicleVo.setCountyName(kxRegion.getName());
        }

        log.info("queryById success! kxVehicleVo = {}", kxVehicleVo.toString());
        return kxVehicleVo;
    }

    /**
     * 查询餐车管理列表
     */
    @Override
    public TableDataInfo<KxVehicleVo> queryPageList(KxVehicleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<KxVehicle> lqw = buildQueryWrapper(bo);
        Page<KxVehicle> pageResult = vehicleMapper.selectPage(pageQuery.build(), lqw);
        List<KxVehicleVo> vehicleVoList = new ArrayList<>();
        if(pageResult != null && pageResult.getRecords().size() > 0){
            for(KxVehicle kxVehicle : pageResult.getRecords()) {
                KxVehicleVo kxVehicleVo = new KxVehicleVo();
                BeanCopyUtils.copy(kxVehicle, kxVehicleVo);
                if (kxVehicle.getProvince() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxVehicle.getProvince());
                    kxVehicleVo.setProvinceName(kxRegion.getName());
                }
                if (kxVehicle.getCity() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxVehicle.getCity());
                    kxVehicleVo.setCityName(kxRegion.getName());
                }
                if (kxVehicle.getCounty() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxVehicle.getCounty());
                    kxVehicleVo.setCountyName(kxRegion.getName());
                }
                vehicleVoList.add(kxVehicleVo);
            }
        }
        Page<KxVehicleVo> retPageResult = new Page<>();
        BeanCopyUtils.copy(pageResult, retPageResult);
        retPageResult.setRecords(vehicleVoList);
        log.info("queryPageList success! retPageResult = {}", retPageResult);
        return TableDataInfo.build(retPageResult);
    }

    /**
     * 查询餐车管理列表
     */
    @Override
    public List<KxVehicleVo> queryList(KxVehicleBo bo) {
        LambdaQueryWrapper<KxVehicle> lqw = buildQueryWrapper(bo);
        List<KxVehicle> vehicleList = vehicleMapper.selectList(lqw);
        List<KxVehicleVo> vehicleVoList = new ArrayList<>();
        if(vehicleList != null && vehicleList.size() > 0){
            for(KxVehicle kxVehicle : vehicleList) {
                KxVehicleVo kxVehicleVo = new KxVehicleVo();
                BeanCopyUtils.copy(kxVehicle, kxVehicleVo);
                if (kxVehicle.getProvince() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxVehicle.getProvince());
                    kxVehicleVo.setProvinceName(kxRegion.getName());
                }
                if (kxVehicle.getCity() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxVehicle.getCity());
                    kxVehicleVo.setCityName(kxRegion.getName());
                }
                if (kxVehicle.getCounty() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxVehicle.getCounty());
                    kxVehicleVo.setCountyName(kxRegion.getName());
                }
                vehicleVoList.add(kxVehicleVo);
            }
        }
        log.info("queryList success! vehicleVoList = {}", vehicleVoList);
        return vehicleVoList;
    }

    private LambdaQueryWrapper<KxVehicle> buildQueryWrapper(KxVehicleBo bo) {
        LambdaQueryWrapper<KxVehicle> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, KxVehicle::getId, bo.getId());
        lqw.eq(StringUtils.isNotEmpty(bo.getVehicleNo()), KxVehicle::getVehicleNo, bo.getVehicleNo());
        lqw.like(StringUtils.isNotEmpty(bo.getVehicleName()), KxVehicle::getVehicleName, bo.getVehicleName());
        lqw.eq(StringUtils.isNotEmpty(bo.getAdcode()), KxVehicle::getAdcode, bo.getAdcode());
        lqw.eq(bo.getProvince() != null, KxVehicle::getProvince, bo.getProvince());
        lqw.eq(bo.getCity() != null, KxVehicle::getCity, bo.getCity());
        lqw.eq(bo.getCounty() != null, KxVehicle::getCounty, bo.getCounty());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), KxVehicle::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getRemark()), KxVehicle::getRemark, bo.getRemark());
        lqw.eq(bo.getState() != null, KxVehicle::getState, bo.getState());
        lqw.eq(bo.getLongitude() != null, KxVehicle::getLongitude, bo.getLongitude());
        lqw.eq(bo.getLatitude() != null, KxVehicle::getLatitude, bo.getLatitude());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), KxVehicle::getPhone, bo.getPhone());
        lqw.like(StringUtils.isNotBlank(bo.getLeaderName()), KxVehicle::getLeaderName, bo.getLeaderName());
        return lqw;
    }

    /**
     * 新增餐车管理
     */
    @Override
    public Boolean insertByBo(KxVehicleBo bo) {
        KxVehicle vehicle = BeanUtil.toBean(bo, KxVehicle.class);
        vehicle.setId(0L);
        //validEntityBeforeSave(vehicle);
        boolean flag = vehicleMapper.insert(vehicle) > 0;
        if (flag) {
            //RedisUtils.deleteKeys(VEHICLE_INFO_PREFIX + "*");
            bo.setId(vehicle.getId());
            log.info("insertByBo success! vehicle = {}", vehicle.toString());
        }
        return flag;
    }

    /**
     * 修改餐车管理
     */
    @Override
    public Boolean updateByBo(KxVehicleBo bo) {
        KxVehicle vehicle = BeanUtil.toBean(bo, KxVehicle.class);
        //validEntityBeforeSave(vehicle);
        boolean b = vehicleMapper.updateById(vehicle) > 0;
        if (b) {
            //RedisUtils.deleteKeys(VEHICLE_INFO_PREFIX + "*");
            log.info("updateByBo success! vehicle = {}", vehicle.toString());
        }
        return b;
    }

    /**
     * 保存前的数据校验
     */
    //private void validEntityBeforeSave(KxVehicle entity) {
    //    //TODO 做一些数据校验,如唯一约束
    //}

    /**
     * 批量删除餐车管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        Boolean ret = (vehicleMapper.deleteBatchIds(ids) > 0);
        if(ret){
            log.info("deleteWithValidByIds success! ids = {}", ids.toString());
        }
        return ret;
    }

    @Override
    public Boolean updateVehicleStateToNormal(KxVehicleBo bo) {
        if (ObjectUtils.isEmpty(bo.getId())) {
            throw new ServiceException("餐车资料不存在");
        }
        if (vehicleMapper.batchUpdateState(Collections.singletonList(bo.getId()), VehicleStatusType.NOMRAL.getCode()) <= 0) {
            throw new ServiceException("餐车资料不存在");
        } else {
            //RedisUtils.deleteKeys(VEHICLE_INFO_PREFIX + "*");
            log.info("updateVehicleStateToNormal success! bo = {}", bo.toString());
        }
        return true;
    }

    @Override
    public Boolean updateVehicleStateToAbort(KxVehicleBo bo) {
        if (ObjectUtils.isEmpty(bo.getId())) {
            throw new ServiceException("餐车资料不存在");
        }
        if (vehicleMapper.batchUpdateState(Collections.singletonList(bo.getId()), VehicleStatusType.ABORT.getCode()) <= 0) {
            throw new ServiceException("餐车资料不存在");
        } else {
            //RedisUtils.deleteKeys(VEHICLE_INFO_PREFIX + "*");
            log.info("updateVehicleStateToAbort success! bo = {}", bo.toString());
        }
        return true;
    }

    @Override
    public Boolean updateBusinessStateToOpen(KxVehicleBo bo) {
        if (ObjectUtils.isEmpty(bo.getId())) {
            throw new ServiceException("餐车资料不存在");
        }
        if (vehicleMapper.batchUpdateOperatingState(Collections.singletonList(bo.getId()), StorageBusinessStatusType.BUSINESS.getCode()) <= 0) {
            throw new ServiceException("餐车资料不存在");
        } else {
            //RedisUtils.deleteKeys(VEHICLE_INFO_PREFIX + "*");
            log.info("updateBusinessStateToOpen success! bo = {}", bo.toString());
        }
        return true;
    }

    @Override
    public Boolean updateBusinessStateToRest(KxVehicleBo bo) {
        if (ObjectUtils.isEmpty(bo.getId())) {
            throw new ServiceException("餐车资料不存在");
        }
        if (vehicleMapper.batchUpdateOperatingState(Collections.singletonList(bo.getId()), StorageBusinessStatusType.REST.getCode()) <= 0) {
            throw new ServiceException("餐车资料不存在");
        } else {
            //RedisUtils.deleteKeys(VEHICLE_INFO_PREFIX + "*");
            log.info("updateBusinessStateToRest success! bo = {}", bo.toString());
        }
        return true;
    }

//    @Override
//    public List<KxVehicleVo> options() {
//        return null;
//    }

    @Override
    public String getVehicleQrcodeImage() {
        return "";
    }

//    @Override
//    public Boolean printTest(KxVehicleBo bo) {
//        return true;
//    }


}
